package com.ysd.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;




//Filter杩囨护鍣�
public class LoginFilter implements Filter {
	// 鏍囩ず绗︼細琛ㄧず褰撳墠鐢ㄦ埛鏈櫥褰�(鍙牴鎹嚜宸遍」鐩渶瑕佹敼涓簀son鏍峰紡)

	String NO_LOGIN = "鎮ㄨ繕鏈櫥褰�";

	// 涓嶉渶瑕佺櫥褰曞氨鍙互璁块棶鐨勮矾寰�(姣斿:娉ㄥ唽鐧诲綍绛�)

	String[] includeUrls = new String[] { "/login", "/register", "/login.html" };

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession(false);
		String uri = request.getRequestURI();
		System.out.println("filter url:" + uri);
		// 鏄惁闇�瑕佽繃婊�
		boolean needFilter = isNeedFilter(uri);
		if (!needFilter) { // 涓嶉渶瑕佽繃婊ょ洿鎺ヤ紶缁欎笅涓�涓繃婊ゅ櫒
			filterChain.doFilter(servletRequest, servletResponse);
		} else { // 闇�瑕佽繃婊ゅ櫒
			// session涓寘鍚玼ser瀵硅薄,鍒欐槸鐧诲綍鐘舵��
			if (session != null && session.getAttribute("user") != null) {
				// System.out.println("user:"+session.getAttribute("user"));
				filterChain.doFilter(request, response);
			} else {
				String requestType = request.getHeader("X-Requested-With");
				// 鍒ゆ柇鏄惁鏄痑jax璇锋眰锛堝洜涓篴jax椤甸潰涓嶈烦杞紝鎵�浠ヨ繖鍧楅渶瑕佸垽鏂竴涓嬶級
				if (requestType != null && "XMLHttpRequest".equals(requestType)) {
					response.getWriter().write(this.NO_LOGIN);
				} else {
					// 閲嶅畾鍚戝埌鐧诲綍椤�(闇�瑕佸湪static鏂囦欢澶逛笅寤虹珛姝tml鏂囦欢)
					response.sendRedirect(request.getContextPath() + "/login.html");
				}
				return;
			}
		}
	}

	/**
	 * @Description: 鏄惁闇�瑕佽繃婊�
	 */
	public boolean isNeedFilter(String uri) {
		for (String includeUrl : includeUrls) {
			if (includeUrl.equals(uri)) {
				return false;
			}
		}
		return true;

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
    public void destroy() {
    }
}
